import json
import random

import requests
import execjs


class TX:
    def __init__(self):
        self.headers = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Origin": "https://captcha.gtimg.com",
            "Pragma": "no-cache",
            "Referer": "https://captcha.gtimg.com/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "cross-site",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
        }

    @classmethod
    def __ease_out_expo(cls, sep):
        if sep == 1:
            return 1
        else:
            return 1 - pow(2, -10 * sep)

    def get_slide_track(self, distance):
        """
        根据滑动距离生成滑动轨迹
        :param distance: 需要滑动的距离
        :return: 滑动轨迹<type 'list'>: [[x,y,t], ...]
            x: 已滑动的横向距离
            y: 已滑动的纵向距离, 除起点外, 均为0
            t: 滑动过程消耗的时间, 单位: 毫秒
        """

        if not isinstance(distance, int) or distance < 0:
            raise ValueError(f"distance类型必须是大于等于0的整数: distance: {distance}, type: {type(distance)}")

        # 记录上一次滑动的距离
        _x = random.randint(40, 80)
        _y = random.randint(200, 220)
        # 初始化轨迹列表
        slide_track = [
            [_x, _y]
        ]
        # 共记录count次滑块位置信息
        count = 30 + int(distance / 2)
        for i in range(count):
            # 已滑动的横向距离
            x = round(self.__ease_out_expo(i / count) * distance)
            # 滑动过程消耗的时间
            if x <= _x:
                continue
            _y += random.choices([0, 1], weights=[9, 1], k=1)[0]
            slide_track.append([x, _y])
            _x = x
        slide_track.append(slide_track[-1])
        return slide_track

    def verify(self, position, prefix, md5):
        url = "https://t.captcha.qq.com/cap_union_new_verify"

        with open('main.js', encoding='utf-8') as f:
            js_code = f.read()
        js = execjs.compile(js_code)

        point_array = position.split('|')
        track = self.get_slide_track(int(point_array[0]) + 30)
        track = [[246,45],[250,52],[290,110],[188,225],[153,209],[152,208],[153,210],[156,213],[153,217],[140,217],[114,214],[82,214],[62,211],[52,209],[48,208],[48,208],[48,207],[56,205],[68,203],[82,203],[90,203],[96,203],[102,203],[108,203],[115,202],[124,202],[132,202],[135,202],[136,202],[139,202],[142,201],[142,201],[143,201],[144,200],[145,199],[145,199]]
        print("滑块轨迹", track)
        collect = js.call("get_collect", track)
        print("collect：", collect)
        eks = js.call("get_info")
        print("eks：", eks)
        pos = js.call("get_pos", int(point_array[0]), int(point_array[1]))
        print("坐标转换：", pos)

        pow_answer = js.call("get_pow_answer", prefix, md5)
        print("坐标转换：", pow_answer)

        collect = "BkIerpyYdRYdOIn+oC31mb3yhqyTcStW/eSxNg9C0T2CCBlE7+izlR0tuwammUiYL4vEjrlYaHgMM61/GOZVhhxyLH4G0pR2YI7pGixs4Jj5IstIbI0hVwGuEGK29N0hsLZ2/hHDMz5gRnXYFbNKpbwk1MvfIgjFqQt4+0dYjZoeklTmiy3RTKrm7uVsWVX2F8+N5xcFz8e4vdlaBA3CbVTUVfpLPA303/TrlO5igOQg7gwMDJC1TNXK21dGEr1xXHoiQFzGAUPXYXQQGQOg3hvK33dESH5Jk1k5HqsUQEcJPrRgCBrPWPjh9jhK1mK6kkfeaxV062gxZV2mUCdy8X9uGRqXKOtNWEAbDdMowNNiVQu6ARadKuKAtMEOUTjxtJ3g9VoqQit5lG6bzDySRWf0GzQ1MQHvNgAI56A8aQapdiMEspKTJPf8I6M0XUhmkR/wnVTj4a3yaVUP/6zJBTLXDYRTYQOsEkfd3JNkXsDnsZd7vy7+t1CEarP+tB69xB+YH7fkF7H/5O7ZcgzyeiCyD5VOxdR6lcPa8pn8Atrfq2ToItbPdmZUrAJgq920ouZoOBSpdDneQZW/3zhrWgh33WJN7sUDeca60D9TPzwozVcCn5MsZyjNVwKfkyxn3Aosqx3o9LFNRklqBUlAjeCnHwnvvH96UtUd4iDO6F4l8PDg3M0kuIIy6s1qx7ulyw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xgD7rSYAPnmmk/y+PRMDqd5HQ1gfVjTKVeZOX1rkjEMhpIF2LLDX0ckurIPCyafz2zbuNF1Zynn2ppWwMKzseSxxVTcAktSgjXBr4zDtWLudONsEu54Q2HZuumE2so7tPNfyVJsXdSwNBkRCEO/4PNZX0/Y1aHcJB0arkJh+3KCxMDtXkJXJSnsMRg2w2egheuFr9BEbimPUVoY2gS/Gk/SMkYNZr78jDQvPIGusIbmNo5Q69tmAyn4XLGY6oUPJC9Mk3jS7a8a4B712U94YjsbfznX25ocOcYhhjlVIBz6/D37S2qWpQPTbbpuT1sUMeqkoXjqiQJqi1q94Few3oVAj+PoqzDV/cAiRW3vOOnGkPppA3F2h6N9wbdj5qQdEgu4G6WT64gua3jHc1o8rp0IDH05MYNkn"

        data = {
            "collect": collect,
            "tlg": len(collect),
            "eks": eks,
            "sess": "s0xlVa7lIIZypp0Y05M_9uMFXwjccEyo2S8W5UTPgyyfcRbmv4hO8bNC2E2uc0xR5RJVkYJg4OexIzkyH5MCHLM5mOnLMa3lJ7WGyCVvMdMTtHBFWOCoCtjzQowni38qcIFOrbUP8HMYMSf8ZMO46VoGQCoevo_denuIYzEK2vtUMjWYWxPXWOXv2hMnRsDWgkXFuKq7GmjP4i7hGyTIoScmeIK9kIuxHvtOuyAYrmKgDYfCdfQnyzX35W7d-QtT_1wt2ujsmLFj6yF4ic2wbYtD87tm2IESCTfyOoI9EC1uBwelpq842o_a5OT-qWjr2Lig_G-cyzPDQzLwOGKHZGlToBABYo6Bbe_zBSxiQjbMbUlNqfQia-IkStEQcEQGteG1jM0Oxxang*",
            "ans": json.dumps([{"elem_id": 1, "type": "DynAnswerType_POS", "data": pos}], separators=(",", ":")),
            "pow_answer": prefix + str(pow_answer['ans']),
            "pow_calc_time": pow_answer['duration']
        }
        response = requests.post(url, headers=self.headers, data=data)

        print(response.text)
        print(response)


if __name__ == '__main__':
    t = TX()
    t.verify("118|82", "4647d8ff14d08565#", "a3b6fcb192299ec4bd44a23bb7a31493")
